// 关于侧边菜单的相关数据以及操作
import { defineStore } from "pinia";
import type { RouteRecordRaw } from "vue-router";
import type { AddRouteType } from "./types";
import { router } from "/@/router";

export const useAddRouteStore = defineStore({
  id: "addRoute", // id必填，且需要唯一
  state: (): AddRouteType => {
    let whiteList: RouteRecordRaw[] = [];
    return { whiteList };
  },
  actions: {
    recurseAddRoute(r: RouteRecordRaw[], name = "Root"): RouteRecordRaw[] {
      // 动态导入vue文件
      const modules = import.meta.glob([
        "../../views/**/*.vue",
        "../../components/**/*.vue",
      ]);
      // 遍历添加router
      const list= r.map((item) => {
        const component = modules[`../..${item.meta?.component}`];
        const obj = {
          name: item.name,
          path: item.path,
          component: component,
          meta: item.meta
        };
        router.addRoute(name, obj);
        if(item.children?.length){
          this.recurseAddRoute(item.children, item.name as string)
        }
        return obj;
      });
      return list;
    },
    setWhiteList() {
      const list = localStorage.getItem("whiteList");
      if (list) {
        this.whiteList = JSON.parse(list);
      } else {
        this.whiteList = [];
      }
    },
    getRouter(r: RouteRecordRaw[]) {
      this.whiteList = r;
      this.recurseAddRoute(r);
      localStorage.setItem("whiteList", JSON.stringify(this.whiteList));
    },
  },
});
